﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows;
using System.Drawing;

namespace QLBH.StandardUI
{
    public class AutoCompleteTextBox:TextBox
    {
        private Control popupControl;

        public Control PopupControl
        {
            get { return popupControl; }
            set 
            { 
                popupControl = value; 
                if (value!=null)
                {
                    popupControl.LostFocus += new EventHandler(popupControl_LostFocus);
                }
            }
        }
        private bool showPopup = true;

        void popupControl_LostFocus(object sender, EventArgs e)
        {
            if (popupControl != null && !this.Focused)
            {
                popupControl.Hide();
            }
        }
        public event EventHandler DataFilterEvent;
             
        public AutoCompleteTextBox()
        {
            this.TextChanged += new EventHandler(AutoCompleteTextBox_TextChanged);
            this.LostFocus += new EventHandler(AutoCompleteTextBox_LostFocus);
            this.MouseEnter += new EventHandler(AutoCompleteTextBox_MouseEnter);
            this.MouseClick += new MouseEventHandler(AutoCompleteTextBox_MouseClick);
        }

        void AutoCompleteTextBox_MouseClick(object sender, MouseEventArgs e)
        {
            this.SelectAll();
        }

        void AutoCompleteTextBox_MouseEnter(object sender, EventArgs e)
        {
            this.SelectAll();

        }

        void AutoCompleteTextBox_LostFocus(object sender, EventArgs e)
        {
            if (popupControl!=null && !popupControl.Focused)
            {
                popupControl.Hide();                  
            }
        }        

        void AutoCompleteTextBox_TextChanged(object sender, EventArgs e)
        {
            if (popupControl!=null && showPopup)
            {
                Point location = new Point();
                location.X = this.Location.X;
                location.Y = this.Location.Y + this.Height;

                popupControl.Location = location;
                if (!this.Parent.Controls.Contains(popupControl))
                {
                    this.Parent.Controls.Add(popupControl);
                    popupControl.BringToFront();
                }
                popupControl.Show();
                if (DataFilterEvent!=null)
                {
                    DataFilterEvent(this, null);
                }
            }
        }
        public void SetText(String text)
        {
            showPopup = false;
            Text = text;
            showPopup = true;
        }

    }
}
